package com.go.where.manager.action.go;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;

import com.go.where.manager.action.SuperAction;
import com.go.where.manager.common.Constants;
import com.go.where.manager.freemarker.CustomFreemarkerManager;
import com.go.where.manager.page.Pagination;
import com.go.where.manager.pojo.ActivityInfo;
import com.go.where.manager.pojo.BigClassInfo;
import com.go.where.manager.pojo.SmallClassInfo;
import com.go.where.manager.pojo.VideoInfo;
import com.go.where.manager.pojo.user.OperatorInfo;
import com.go.where.manager.service.ActivityService;
import com.go.where.manager.service.BigClassService;
import com.go.where.manager.service.VideoService;
import com.go.where.manager.service.system.OperatorService;
import com.go.where.manager.util.CommonUtil;
import com.go.where.manager.util.CompressPicUtil;
import com.go.where.manager.util.DateUtil;

@InterceptorRefs( {
		@InterceptorRef(value = "defaultStack", params = { "maximumSize",
				"2048000", "allowedTypes",
				"image/bmp,image/png,image/gif,image/jpeg" }),
		@InterceptorRef(value = "defalutStackSet") })
public class VideoAction extends SuperAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4383195694100314090L;
	private static final Logger log = Logger.getLogger(VideoAction.class);

	public Pagination<?> page;

	@Resource(name = "bigClassService")
	private BigClassService bigClassService;
	@Resource(name = "videoService")
	private VideoService videoService;
	@Resource(name = "activityService")
	private ActivityService activityService;
	@Resource
	private OperatorService operatorService;

	private VideoInfo videoInfo;
	private VideoInfo videoInfoQuery;

	private List<BigClassInfo> bigClassList;
	private List<SmallClassInfo> smallClassList;

	private String videoId;

	private File videoCover;// 上传的文件
	private String videoCoverFileName; // 文件名称
	private String videoCoverContentType; // 文件类型

	private List<ActivityInfo> activitys;

	/**
	 * 查询列表
	 * 
	 * @return
	 */
	public String list() {
		if (videoInfoQuery == null) {
			videoInfoQuery = new VideoInfo();
			videoInfoQuery.setPageSize(Constants.INIT_PAGESIZE);
			videoInfoQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
		}
		try {
			String userId = getCurrentOperator().getUserId();
			OperatorInfo op = operatorService.queryOperatorInfoByUserId(userId);
			if (op != null) {
				String roleId = op.getRoleId();
				if (CustomFreemarkerManager.getValue("system.merchant.role.id")
						.equals(roleId)) {
					videoInfoQuery.setMroleId(roleId);
				}
			}
			videoInfoQuery.setIsDelete(Constants.NOT_DELETED);
			page = videoService.queryPage(videoInfoQuery);
		} catch (Exception e) {
			addActionError(e.getMessage());
			log.error("查询信息异常", e);
		}
		return LIST;
	}

	public String toEdit() {
		OperatorInfo op = operatorService
				.queryOperatorInfoByUserId(getCurrentOperator().getUserId());
		String mroleId = null;
		if (op != null) {
			String roleId = op.getRoleId();
			if (CustomFreemarkerManager.getValue("system.merchant.role.id")
					.equals(roleId)) {
				mroleId = roleId;
			}
		}
		BigClassInfo bi = new BigClassInfo();
		bi.setMroleId(mroleId);
		bigClassList = bigClassService.queryAll(bi);
		ActivityInfo ai = new ActivityInfo();
		ai.setMroleId(mroleId);
		activitys = activityService.queryAll(ai);
		videoInfo = videoService.queryByPrimartKey(videoId);
		return INPUT;
	}

	public String add() {
		OperatorInfo op = operatorService
				.queryOperatorInfoByUserId(getCurrentOperator().getUserId());
		String mroleId = null;
		if (op != null) {
			String roleId = op.getRoleId();
			if (CustomFreemarkerManager.getValue("system.merchant.role.id")
					.equals(roleId)) {
				mroleId = roleId;
			}
		}
		BigClassInfo bi = new BigClassInfo();
		bi.setMroleId(mroleId);
		bigClassList = bigClassService.queryAll(bi);
		ActivityInfo ai = new ActivityInfo();
		ai.setMroleId(mroleId);
		activitys = activityService.queryAll(ai);
		return INPUT;
	}

	/**
	 * 保存
	 * 
	 * @return
	 */
	public String save() {
		try {
			String coverRealpath = ServletActionContext.getServletContext()
					.getRealPath(
							CommonUtil.FILE_SEPARATOR
									+ Constants.VIDEO_COVER_IMAGES);
			// 上传视频封面
			uploadPicture(videoInfo, videoCover, videoCoverFileName,
					coverRealpath);
			videoInfo.setActivityId(videoInfo.getActivityTitle());
			videoService.save(videoInfo, getCurrentOperator());
			redirectionUrl = "video!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("保存信息异常", e);
			addActionError("保存信息异常！" + e);
			return this.add();
		}
	}

	/**
	 * 编辑
	 * 
	 * @return
	 */
	public String edit() {
		try {
			String coverRealpath = ServletActionContext.getServletContext()
					.getRealPath(
							CommonUtil.FILE_SEPARATOR
									+ Constants.VIDEO_COVER_IMAGES);
			// 上传视频封面
			uploadPicture(videoInfo, videoCover, videoCoverFileName,
					coverRealpath);
			videoInfo.setActivityId(videoInfo.getActivityTitle());
			videoService.update(videoInfo, getCurrentOperator());
			redirectionUrl = "video!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("修改信息异常", e);
			addActionError("修改信息异常！" + e);
			videoId = videoInfo.getVideoId();
			return this.toEdit();
		}
	}

	/**
	 * 详情
	 * 
	 * @return
	 */
	public String detail() {
		videoInfo = videoService.queryByPrimartKey(videoId);
		OperatorInfo op = operatorService
				.queryOperatorInfoByUserId(getCurrentOperator().getUserId());
		String mroleId = null;
		if (op != null) {
			String roleId = op.getRoleId();
			if (CustomFreemarkerManager.getValue("system.merchant.role.id")
					.equals(roleId)) {
				mroleId = roleId;
			}
		}
		BigClassInfo bi = new BigClassInfo();
		bi.setMroleId(mroleId);
		bigClassList = bigClassService.queryAll(bi);
		return "detail";
	}

	/**
	 * 假删除
	 * 
	 * @return
	 */
	public String falseDelete() {
		videoInfo = new VideoInfo();
		videoInfo.setVideoId(videoId);
		videoInfo.setIsDelete(Constants.DELETED);
		try {
			videoService.update(videoInfo, getCurrentOperator());
			redirectionUrl = "video!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("删除信息异常", e);
			addActionError("删除信息异常" + e);
			return this.list();
		}
	}

	private void uploadPicture(VideoInfo videoInfo, File picture,
			String pictureFileName, String picRealpath)
			throws UnsupportedEncodingException, FileNotFoundException,
			IOException {
		StringBuilder picPath = new StringBuilder();
		ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
		String realpath = picRealpath;
		File file = picture;
		if (file != null) {
			File savedir = new File(realpath);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
			String newFileName = DateUtil.format(new Date(), "yyyyMMddHHmmss")
					+ "_" + CommonUtil.createRandomNumber()
					+ pictureFileName.substring(pictureFileName.indexOf("."));
			FileOutputStream fos = new FileOutputStream(realpath
					+ CommonUtil.FILE_SEPARATOR + newFileName);
			picPath.append(CommonUtil.FILE_SEPARATOR
					+ Constants.VIDEO_COVER_IMAGES);

			picPath.append(Constants.ZOOM_PATH + CommonUtil.FILE_SEPARATOR
					+ newFileName);
			try {
				CompressPicUtil.compressPicture(realpath, newFileName, file);
				FileInputStream fis = new FileInputStream(file);
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = fis.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
				fis.close();
				fos.close();
			} catch (Exception e) {
				log.error("", e);
			}
		}

		if (picPath != null && picPath.toString().length() > 0) {
			videoInfo.setVideoCover(picPath.toString());
		}
	}

	public Pagination<?> getPage() {
		return page;
	}

	public void setPage(Pagination<?> page) {
		this.page = page;
	}

	public List<BigClassInfo> getBigClassList() {
		return bigClassList;
	}

	public void setBigClassList(List<BigClassInfo> bigClassList) {
		this.bigClassList = bigClassList;
	}

	public List<SmallClassInfo> getSmallClassList() {
		return smallClassList;
	}

	public void setSmallClassList(List<SmallClassInfo> smallClassList) {
		this.smallClassList = smallClassList;
	}

	public VideoInfo getVideoInfo() {
		return videoInfo;
	}

	public void setVideoInfo(VideoInfo videoInfo) {
		this.videoInfo = videoInfo;
	}

	public VideoInfo getVideoInfoQuery() {
		return videoInfoQuery;
	}

	public void setVideoInfoQuery(VideoInfo videoInfoQuery) {
		this.videoInfoQuery = videoInfoQuery;
	}

	public String getVideoId() {
		return videoId;
	}

	public void setVideoId(String videoId) {
		this.videoId = videoId;
	}

	public File getVideoCover() {
		return videoCover;
	}

	public void setVideoCover(File videoCover) {
		this.videoCover = videoCover;
	}

	public String getVideoCoverFileName() {
		return videoCoverFileName;
	}

	public void setVideoCoverFileName(String videoCoverFileName) {
		this.videoCoverFileName = videoCoverFileName;
	}

	public String getVideoCoverContentType() {
		return videoCoverContentType;
	}

	public void setVideoCoverContentType(String videoCoverContentType) {
		this.videoCoverContentType = videoCoverContentType;
	}

	public List<ActivityInfo> getActivitys() {
		return activitys;
	}

	public void setActivitys(List<ActivityInfo> activitys) {
		this.activitys = activitys;
	}

}
